import Icon from '@/components/Icon'
import { useInitialState } from '@/hooks/use-initial-state'
import {
  getALlChannel,
  getUserChannel,
  setActiveChannel
} from '@/store/actions/home'
import { Popup, Tabs } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import ArticleList from './ArticleList'
import Channels from './Channels'

import styles from './index.module.scss'

const Home = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const { userChannels, activeChannelId } = useInitialState(getUserChannel).home

  useEffect(() => {
    // 进入页面时获得所有数据
    dispatch(getALlChannel())

    // 设置默认激活频道
    dispatch(setActiveChannel(userChannels[0]?.id))
  }, [dispatch, userChannels])

  const [channelPopupVisible, setChannelPopupVisible] = useState(false)

  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      <Tabs
        className="tabs"
        activeLineMode="fixed"
        activeKey={'' + activeChannelId}
        onChange={(key) => {
          dispatch(setActiveChannel(+key))
        }}
      >
        {userChannels.map((item) => (
          <Tabs.Tab title={item.name} key={item.id}>
            {item.name}
            <ArticleList channelId={item.id} />
          </Tabs.Tab>
        ))}
      </Tabs>
      <div className="tabs-opration">
        <Icon
          name="iconbtn_search"
          onClick={() => {
            history.push('/search')
          }}
        />
        <Icon
          name="iconbtn_channel"
          onClick={() => setChannelPopupVisible(true)}
        />
      </div>

      <Popup visible={channelPopupVisible} position="left">
        <Channels
          onClose={() => {
            setChannelPopupVisible(false)
          }}
        />
      </Popup>
    </div>
  )
}

export default Home
